package order

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"go-papers/common/go-wechat/common"
	"go-papers/constant"
	"go-papers/logic"
	"go-papers/models"
	"go-papers/models/protocols"
	"go-papers/notice"
	"go-papers/pkg/lognew"
	"go-papers/pkg/wechat"
	"go-papers/tools"
	"go-papers/tools/app"
)

func RefundCheck(c *gin.Context) {
	orderIdStr := c.Request.FormValue("orderId")
	if orderIdStr == "" {
		app.CommonResp(c, -1, "订单信息有误/orderId", nil)
		return
	}
	orderId, _ := tools.StringToInt(orderIdStr)
	if orderId == 0 {
		app.CommonResp(c, -1, "订单信息有误/orderId", orderIdStr)
		return
	}

	//查询订单状态
	var order models.Order
	orderInfo, err := order.GetByID(orderId)
	if err != nil {
		app.CommonResp(c, -1, "订单信息有误:"+err.Error(), nil)
		return
	}
	if orderInfo.OrderId == 0 {
		app.CommonResp(c, -1, "订单信息有误:记录不存在", orderInfo)
		return
	}

	//更新退款记录
	var rf models.OrderRefund
	resu, err := rf.GetByID(orderInfo.OrderId, orderInfo.MemberId)
	if err != nil {
		app.CommonResp(c, -1, "订单信息退款记录有误:记录不存在", orderInfo)
		return
	}
	checkInfo := c.Request.FormValue("closeReson")
	if checkInfo == "" {
		app.CommonResp(c, -1, "请填写订单退款审核原因", orderIdStr)
		return
	}

	uid := tools.GetUserId(c)
	uName := tools.GetUserName(c)

	// orderStatus: 70
	//closeReson: 测试退款1
	//organPrice: 0
	//organMomPrice: 0
	//memberMomPrice: 0
	//systemPrice: 10
	//orderId: 189
	//审核订单状态 65 / 70
	orderStatus := c.Request.FormValue("orderStatus")
	if orderStatus == "70" {

		//分别生成  佣金 结算记录 待退回
		priceOrgan := tools.StringToFloat64(err, c.Request.FormValue("organPrice"))
		if priceOrgan <= 0 {
			priceOrgan = 0
		}
		priceOrganMom := tools.StringToFloat64(err, c.Request.FormValue("organMomPrice"))
		if priceOrganMom <= 0 {
			priceOrganMom = 0
		}
		priceMemberMom := tools.StringToFloat64(err, c.Request.FormValue("memberMomPrice"))
		if priceMemberMom <= 0 {
			priceMemberMom = 0
		}
		priceSystem := tools.StringToFloat64(err, c.Request.FormValue("systemPrice"))
		if priceSystem <= 0 {
			priceSystem = 0
		}

		refundPrice := priceOrgan + priceOrganMom + priceMemberMom + priceSystem
		if refundPrice <= 0 {
			app.CommonResp(c, -1, "订单信息退款记录有误:退款金额为0", orderInfo)
			return
		}

		// 查询实际分佣金状态
		var orderS models.OrderShare
		orderS.OrderId = orderId
		shareList := orderS.GetList()
		if len(shareList) > 0 {
			//// 类型 1平台与机构 2 社区达人与拓展用户 3 社区达人与拓展机构
			for _, v := range shareList {
				// 分成状态 ：分成状态 1  待确认  5 已确认/已打款  10 待退回 20 已退回 50 取消关闭
				if v.ShareStatus == "1" {
					v.ShareStatus = "50"
					_, _ = v.Update(v.OrderShareId)
				}
			}
		}

		// 获取 一条记录
		if priceOrgan > 0 || priceOrganMom > 0 || priceMemberMom > 0 {
			var oor models.OrderShare
			first, err := oor.GetFirst(orderInfo.OrderId)
			if err != nil {
				app.CommonResp(c, -1, "订单信息退款记录流水查询有误："+err.Error(), orderInfo)
				return
			}
			//生成流水
			now := time.Now().Format("2006-01-02 15:04:05")
			if priceOrgan > 0 {
				or1 := models.OrderShare{
					OrderId:             orderInfo.OrderId,
					ShareName:           "机构",
					ShareStatus:         "10",
					ShareDesc:           "订单退款/机构课程费用退回用户",
					SharePrice:          priceOrgan,
					ShareRate:           priceOrgan / orderInfo.OrderPrice,
					ShareType:           "1",
					ShareUserId:         orderInfo.OrganId,
					ShareTo:             1,
					ShareTime:           now,
					ShareMomOrganPrice:  first.ShareMomOrganPrice,
					ShareMomOrganRate:   first.ShareMomOrganRate,
					ShareMomMemberPrice: first.ShareMomMemberPrice,
					ShareMomMemberRate:  first.ShareMomMemberRate,
					ShareOrganPrice:     first.ShareOrganPrice,
					ShareOrganRate:      first.ShareOrganRate,
					ShareMomLevel:       first.ShareMomLevel,
				}
				_, err = or1.Create()
				if err != nil {
					lognew.Error(c, "OrderShareInsertError", lognew.Fields{"or1": or1, "err": err.Error()})
				}
			}

			if priceMemberMom > 0 {
				or1 := models.OrderShare{
					OrderId:             orderInfo.OrderId,
					ShareName:           orderInfo.MemberMomName,
					ShareStatus:         "10",
					ShareDesc:           "订单退款/拓展用户社区达人佣金退回",
					SharePrice:          priceMemberMom,
					ShareRate:           priceMemberMom / orderInfo.OrderPrice,
					ShareType:           "3",
					ShareUserId:         orderInfo.MemberMomId,
					ShareTo:             1,
					ShareTime:           now,
					ShareMomOrganPrice:  first.ShareMomOrganPrice,
					ShareMomOrganRate:   first.ShareMomOrganRate,
					ShareMomMemberPrice: first.ShareMomMemberPrice,
					ShareMomMemberRate:  first.ShareMomMemberRate,
					ShareOrganPrice:     first.ShareOrganPrice,
					ShareOrganRate:      first.ShareOrganRate,
					ShareMomLevel:       first.ShareMomLevel,
				}
				_, err = or1.Create()
				if err != nil {
					lognew.Error(c, "OrderShareInsertError", lognew.Fields{"or1": or1, "err": err.Error()})
				}
			}

			if priceOrganMom > 0 {
				var organ models.Organ
				organInfo, _ := organ.GetByID(orderInfo.OrganId)

				or1 := models.OrderShare{
					OrderId:             orderInfo.OrderId,
					ShareName:           organInfo.OrganMomName,
					ShareStatus:         "10",
					ShareDesc:           "订单退款/拓展机构社区达人退回佣金",
					SharePrice:          priceOrganMom,
					ShareRate:           priceOrganMom / orderInfo.OrderPrice,
					ShareType:           "2",
					ShareUserId:         organInfo.OrganMomId,
					ShareTo:             1,
					ShareTime:           now,
					ShareMomOrganPrice:  first.ShareMomOrganPrice,
					ShareMomOrganRate:   first.ShareMomOrganRate,
					ShareMomMemberPrice: first.ShareMomMemberPrice,
					ShareMomMemberRate:  first.ShareMomMemberRate,
					ShareOrganPrice:     first.ShareOrganPrice,
					ShareOrganRate:      first.ShareOrganRate,
					ShareMomLevel:       first.ShareMomLevel,
				}
				_, err = or1.Create()
				if err != nil {
					lognew.Error(c, "OrderShareInsertError", lognew.Fields{"or1": or1, "err": err.Error()})
				}
			}
		}

		// 调用微信 分账回退 判断订单是否有分账
		returnNo := ""
		returnStatus := ""
		returnMsg := ""
		pprice := priceOrganMom + priceMemberMom
		if orderInfo.ShareNo != "" && pprice > 0 && orderInfo.ShareAccountPrice > 0 {
			returnNo = logic.GetTradeNo(orderInfo.OrderId, "R")
			// 进行分账回退
			params := &common.OrderShareReturn{
				Base: common.Base{
					SubMchId: orderInfo.OrganPayAccount,
				},
				OrderId:           "",
				OutTradeNo:        orderInfo.ShareNo,
				OutReturnNo:       returnNo,
				ReturnAccountType: "MERCHANT_ID",
				ReturnAccount:     orderInfo.ShareAccount,
				ReturnAmount:      int(pprice * 100),
				Description:       "用户退款",
			}
			rr, err := wechat.Server.WechatPay().ShareReturn(params)
			lognew.Info(c, "returnlogBack", lognew.Fields{"rr": rr, "params": params})

			if err != nil {
				returnMsg = err.Error()
				lognew.Error(c, "ShareReturnError", lognew.Fields{"err": returnMsg, "params": params})
			}

			ReturnInfo, _ := json.Marshal(params)
			BackInfo := ""
			if rr != nil {
				returnStatus = rr.Result
				nr, _ := json.Marshal(rr)
				BackInfo = string(nr)
			}
			// 数据处理 记录log
			returnlog := models.OrderReturnLog{
				OrderId:       orderInfo.OrderId,
				OrderPrice:    orderInfo.OrderPrice,
				ReturnPrice:   pprice,
				ReturnAccount: orderInfo.ShareAccount,
				ReturnNo:      returnNo,
				ReturnStatus:  returnStatus,
				ReturnInfo:    string(ReturnInfo),
				BackInfo:      BackInfo,
			}
			_, err = returnlog.Create()
			if err != nil {
				lognew.Error(c, "returnlogError", lognew.Fields{"returnlog": returnlog, "err": err.Error()})
			}
		}

		//更新 退款记录
		resu.CheckInfo = checkInfo
		resu.RefundStatus = "10"
		resu.RefundPrice = refundPrice
		resu.RefundOrganPrice = priceOrgan
		resu.RefundOrganMomPrice = priceOrganMom
		resu.RefundMemberMomPrice = priceMemberMom
		resu.ReturnNo = returnNo
		resu.ReturnStatus = returnStatus
		resu.UserId = tools.GetUserId(c)
		resu.UserName = tools.GetUserName(c)
		resu.CheckTime = time.Now().Format("2006-01-02 15:04:05")
		_, err = resu.Update(resu.Id)
		if err != nil {
			app.CommonResp(c, -1, "订单信息退款记录跟新失败"+err.Error(), orderInfo)
			return
		}

		//更新订单状态
		var ord models.Order
		ord.OrderStatus = constant.ORDER_STATUS_70
		ord.ShareOrganRefund = priceOrgan
		newOrder, _ := ord.Update(orderInfo.OrderId)

		//用户操作订单记录
		orlog := models.OrderOprateLog{
			OrderId:         orderInfo.OrderId,
			Title:           "订单退款审核通过",
			Desc:            "订单退款审核通过/操作人：" + uName + " /" + checkInfo,
			LogType:         "1",
			OrderStatusName: tools.OrderStatusName(ord.OrderStatus),
			PayStatusName:   tools.PayStatusName(ord.PayTime, ord.RefundTime),
			LogName:         "订单退款审核通过",
			LogUid:          uid,
		}
		_, err = orlog.Create() // 订单退款审核通过
		if err != nil {
			lognew.Error(c, "LogCreate", lognew.Fields{"err": err.Error()})
		}

		go notice.NoticeByType(notice.OrderRefundCheck, orderInfo.OrderId, 0, uid) // 用户订单退款审核通过

		// 退款操作
		logic.OrderChangeInfoRefund(newOrder, refundPrice)

		app.CommonResp(c, 0, "操作成功", nil)
		return
	}

	//更新 退款记录
	resu.CheckInfo = checkInfo
	resu.RefundStatus = "5"
	resu.UserId = tools.GetUserId(c)
	resu.UserName = tools.GetUserName(c)
	resu.CheckTime = time.Now().Format("2006-01-02 15:04:05")
	_, err = resu.Update(resu.Id)
	if err != nil {
		app.CommonResp(c, -1, "订单信息退款记录跟新失败"+err.Error(), orderInfo)
		return
	}

	var ord models.Order
	ord.OrderStatus = constant.ORDER_STATUS_65
	_, _ = ord.Update(orderInfo.OrderId)

	//用户操作订单记录
	orlog := models.OrderOprateLog{
		OrderId:         orderInfo.OrderId,
		Title:           "订单退款审核不通过",
		Desc:            "订单退款审核不通过/操作人：" + uName + " /" + checkInfo,
		LogType:         "1",
		OrderStatusName: tools.OrderStatusName(ord.OrderStatus),
		PayStatusName:   tools.PayStatusName(ord.PayTime, ord.RefundTime),
		LogName:         "订单退款审核不通过",
		LogUid:          uid,
	}
	_, _ = orlog.Create() // 订单退款审核不通过
	app.CommonResp(c, 0, "操作成功", nil)

}

type DataRefundJson struct {
	OrderId   int    `json:"orderId" `
	SureCheck string `json:"sureCheck" `
}

func Refund(c *gin.Context) {
	var dataJson DataRefundJson

	//var data models.Member
	err := c.BindWith(&dataJson, binding.JSON)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}

	orderId := dataJson.OrderId     // c.Request.FormValue("orderId")
	sureCheck := dataJson.SureCheck // c.Request.FormValue("sureCheck")
	if orderId == 0 {
		app.CommonResp(c, -1, "订单信息有误/orderId", nil)
		return
	}

	//查询订单状态
	var order models.Order
	orderInfo, err := order.GetByID(orderId)
	if err != nil {
		app.CommonResp(c, -1, "订单信息有误:"+err.Error(), nil)
		return
	}
	if orderInfo.OrderId == 0 {
		app.CommonResp(c, -1, "订单信息有误:记录不存在", orderInfo)
		return
	}

	//查询是否有待退回的佣金
	// 查询实际分佣金状态
	var orderS models.OrderShare
	orderS.OrderId = orderId
	shareList := orderS.GetList()
	errMsg := ""
	if len(shareList) > 0 {
		//// 类型 1平台与机构 2 社区达人与拓展用户 3 社区达人与拓展机构
		for _, v := range shareList {
			// 分成状态 ：分成状态 1  待确认  5 已确认/已打款   10 待退回 20 已退回 50 取消关闭
			if v.ShareStatus == "10" {
				errMsg = "#" + tools.IntToString(v.OrderShareId) + "#" + v.ShareName + " 待退回 (" + v.ShareDesc + ")"
				break
			}
		}
	}

	if errMsg != "" && sureCheck != "ok" {
		app.CommonResp(c, -1, "订单信息有待确认退回的佣金:"+errMsg, orderInfo)
		return
	}

	//退款金额 为空时，直接使用订单金额 全额退款
	if orderInfo.RefundPrice == 0 {
		orderInfo.RefundPrice = orderInfo.OrderPrice
	}

	//退款订单号
	tradeNo := logic.GetTradeNo(orderId, "R")
	orderInfo.RefundNo = tradeNo
	orderInfo.OrderStatus = constant.ORDER_STATUS_80
	_, _ = orderInfo.Update(orderInfo.OrderId)

	//进行订单退款
	refundData := &common.OrderRefund{}
	refundData.TotalFee = int(orderInfo.OrderPrice * 100)   // 订单金额	total_fee
	refundData.OutTradeNo = orderInfo.PayTradeNo            // 商户订单号
	refundData.OutRefundNo = tradeNo                        //商户退款单号
	refundData.RefundFee = int(orderInfo.RefundPrice * 100) // 退款金额
	refundData.SubMchId = orderInfo.OrganPayAccount
	esp, err := wechat.Server.WechatPay().Refund(refundData)
	if err != nil {
		app.CommonResp(c, 0, "订单进行微信退款操作异常："+err.Error(), esp)
		return
	}
	if esp.ReturnCode == "FAIL" {
		app.CommonResp(c, 0, "订单进行微信退款操作失败："+esp.ReturnMsg, refundData)
		return
	}
	s, _ := json.Marshal(esp)
	//生产 trade 订单记录
	orderTrade := models.OrderTrade{
		OrderId:       orderInfo.OrderId,
		TradeMemberId: orderInfo.MemberId,
		TradeNo:       tradeNo,
		TradePrice:    orderInfo.RefundPrice,
		TradeBody:     "订单申请退款",
		TradeAppId:    esp.AppId,
		TradeMechId:   esp.MchId,
		TradeOpenId:   "",
		TradeStart:    time.Now().Format("2006-01-02 15:04:05"),
		TradeCallUrl:  "",
		TradeResult:   esp.ReturnMsg,
		TradeInfo:     string(s),
		TradeStatus:   "1",
	}
	_, err = orderTrade.Create()
	if err != nil {
		lognew.Info(c, "orderTrade_error", lognew.Fields{"error": err.Error(), "orderTrade": orderTrade})
	}

	lognew.Info(c, "refundData", lognew.Fields{"esp": esp, "refund_data": refundData, "orderInfo": orderInfo, "err": err})
	//-----//
	uid := tools.GetUserId(c)
	uName := tools.GetUserName(c)

	//用户操作订单记录
	orlog := models.OrderOprateLog{
		OrderId:         orderInfo.OrderId,
		Title:           "订单退款确认",
		Desc:            "订单退款确认/操作人：" + uName + "/退款金额：" + fmt.Sprintf("%0.2f", orderInfo.RefundPrice),
		LogType:         "1",
		OrderStatusName: tools.OrderStatusName(orderInfo.OrderStatus),
		PayStatusName:   tools.PayStatusName(orderInfo.PayTime, orderInfo.RefundTime),
		LogName:         "订单退款确认",
		LogUid:          uid,
	}
	_, _ = orlog.Create() // 订单退款确认

	go notice.NoticeByType(notice.OrderRefundSuccess, orderInfo.OrderId, 0, uid) // 用户订单退款确认

	app.CommonResp(c, 0, "订单进行微信退款操作成功", esp)

}

//    机构课程费用退款：  ___ 元       [ 默认填写可退最大金额  接口返回 ] --- 生成 资金待退回的 佣金结算记录
//    机构社区达人退款：  ___ 元       [ 默认填写可退最大金额  接口返回 ] --- 生成 资金待退回的 佣金结算记录
//    用户社区达人退款:     ___ 元       [ 默认填写可退最大金额  接口返回 ] --- 生成 资金待退回的 佣金结算记录
func RefundPre(c *gin.Context) {

	orderIdStr := c.Request.FormValue("orderId")
	if orderIdStr == "" {
		app.CommonResp(c, -1, "订单信息有误/orderId", nil)
		return
	}
	orderId, _ := tools.StringToInt(orderIdStr)
	if orderId == 0 {
		app.CommonResp(c, -1, "订单信息有误/orderId", orderIdStr)
		return
	}

	//查询订单状态
	var order models.Order
	orderInfo, err := order.GetByID(orderId)
	if err != nil {
		app.CommonResp(c, -1, "订单信息有误:"+err.Error(), nil)
		return
	}
	if orderInfo.OrderId == 0 {
		app.CommonResp(c, -1, "订单信息有误:记录不存在", orderInfo)
		return
	}

	// 返回
	resp := protocols.OrderRefundPre{
		OrganPrice:     0,
		OrganMomPrice:  0,
		MemberMomPrice: 0,
		OrderPrice:     orderInfo.OrderPrice,
		SystemPrice:    0,
	}

	yogi := 0.0
	a := 0.0
	b := 0.0
	d := 0.0
	// 查询实际分佣金状态
	var orderS models.OrderShare
	orderS.OrderId = orderId
	shareList := orderS.GetList()
	if len(shareList) > 0 {
		//// 类型 1平台与机构 3 社区达人与拓展用户 2 社区达人与拓展机构
		for _, v := range shareList {
			// 分成状态 ：分成状态 1  待确认  5 已确认/已打款   10 待退回 20 已退回 50 取消关闭
			if v.ShareStatus == "1" || v.ShareStatus == "5" {
				if v.ShareType == "1" {
					a += v.SharePrice
				}
				if v.ShareType == "2" {
					b += v.SharePrice
				}
				if v.ShareType == "3" {
					d += v.SharePrice
				}
			}

			if v.ShareStatus == "10" || v.ShareStatus == "20" {
				if v.ShareType == "1" {
					a -= v.SharePrice
				}
				if v.ShareType == "2" {
					b -= v.SharePrice
				}
				if v.ShareType == "3" {
					d -= v.SharePrice
				}
			}

		}
		yogi = a + b + d
	}

	ll := orderInfo.OrderPrice - yogi
	resp.SystemPrice = tools.Decimal(ll)
	resp.OrganPrice = a
	resp.OrganMomPrice = b
	resp.MemberMomPrice = d
	app.CommonResp(c, 0, "查询成功", resp)

}
